package com.fy.card.service.impl;

import com.fy.card.entity.User;
import com.fy.card.mapper.UserMapper;
import com.fy.card.service.intf.UserService;
import com.google.common.base.Joiner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper mapper;

    @Override
    public User login(String username, String password) {
      List<User> users = mapper.selectByName(username);
        //判断密码
        for (User user : users) {
            if (Objects.equals(password,user.getPassword())){
                return user;
            }
        }
        return null;
    }

    @Override
    public User likeCard(Integer userId, Integer cardId, Boolean like) {
      //喜欢哪个名片  不喜欢要【删除】哪个名片
        User user = mapper.selectByPrimaryKey(userId);
        //喜欢的有哪些名片 1，2，3，4
        String likedIds = user.getLiked();
        if (like){
            //喜欢哪个名片  liked 追加名片id
            likedIds = StringUtils.isEmpty(likedIds) ? cardId.toString() : likedIds + "," + cardId;
        }else {
            //不喜欢 删除
            //数组转换成一个流  用流的方式创建一个新的集合
            List<String> likedIdList = Arrays.stream(likedIds.split(",")).collect(Collectors.toList());
           //这个新的集合 执行remove操作
            likedIdList.remove(cardId.toString());
            //把这个集合转换为逗号分割的字串 Google提供了一个工具 guava jar包
            likedIds =  Joiner.on(",").join(likedIdList);
        }
        user.setLiked(likedIds);
        mapper.updateByPrimaryKeySelective(user);
        return user;
    }

    //测试 使用Google提供的工具 guava 把【数组】或者【集合】通过定义的字符 进行字符串拼接
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(123, 2343, 35, 456, 56);
        System.out.println(Joiner.on(",").join(list));


    }
}
